package com.zz.yt.lib.login.delegate.login;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ResourceUtils;
import com.whf.android.jar.util.log.LatteLogger;
import com.zz.yt.lib.login.R;
import com.zz.yt.lib.login.checker.TravelManager;
import com.zz.yt.lib.login.constant.ILoginListener;
import com.zz.yt.lib.login.constant.ISignUpListener;
import com.zz.yt.lib.login.delegate.login.base.BaseFingerDelegate;
import com.zz.yt.lib.login.delegate.login.base.BaseSigInDelegate;
import com.zz.yt.lib.ui.view.SelectCheckView;


/**
 * 登录
 *
 * @author qf
 * @version 2023-1-03
 */
public class LoginTravelDelegate extends BaseFingerDelegate implements View.OnTouchListener {


    private EditText idEditPassword;
    private Button loginSign;

    private SelectCheckView viewSelect = null;
    private ILoginListener mLoginListener = null;
    private ISignUpListener mSignUpListener = null;

    @Override
    public void onAttach(@NonNull Context activity) {
        super.onAttach(activity);
        //这里是类型转换，而不是判断
        if (activity instanceof ILoginListener) {
            mLoginListener = (ILoginListener) activity;
        }
        if (activity instanceof ISignUpListener) {
            mSignUpListener = (ISignUpListener) activity;
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.hai_delegate_login_travel;
    }

    private void inBundle() {
        if (mLoginListener != null) {
            Object launcher = mLoginListener.setSignIn();
            if (launcher != null) {
                if (launcher instanceof Integer) {
                    getImageView(R.id.login_image_background)
                            .setImageResource((int) launcher);
                } else if (launcher instanceof View) {
                    View viewLauncher = (View) launcher;
                    RelativeLayout view = findViewById(R.id.login_layout_background);
                    ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT);
                    viewLauncher.setLayoutParams(layoutParams);
                    view.addView(viewLauncher);
                }
            }
        }

        //设置是否保存登录信息
        setSelect(true);

        viewSelect = findViewById(R.id.login_check_acc_pass);
        setImgSelect();

        //注册
        boolean isSignUp = false;
        if (mSignUpListener != null) {
            isSignUp = mSignUpListener.isSignUp();
            mSignUpListener.setSignUpView(mRootView, getTextView(R.id.login_text_sign_up));
        }
        getTextView(R.id.login_text_sign_up).setVisibility(isSignUp ? View.VISIBLE : View.GONE);
    }

    /*** 设置是否一周内自动登录 */
    private void setImgSelect() {
        if (viewSelect != null) {
            viewSelect.setChecked(TravelManager.isTravel());
            viewSelect.setOnClickListener(v -> {
                viewSelect.select();
                TravelManager.setRoleState(viewSelect.isChecked());
            });
        }
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        inBundle();
        initView();
        inGradePermission();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        idEditPassword = getEditText(R.id.login_edit_password);
        loginSign = getButton(R.id.login_btn_sign_in);
        idEditPassword.addTextChangedListener(this);
        idEditPassword.setOnTouchListener(this);

        getEditText(R.id.login_edit_account).setText(getAccount());

        getEditText(R.id.login_edit_password).setText(getPassword());
    }

    /**
     * EditText的drawableRight属性设置点击事件
     */
    @SuppressLint("ClickableViewAccessibility")
    public boolean onTouch(View v, MotionEvent event) {
        // 得到一个长度为4的数组，分别表示左上右下四张图片(0.1.2.3)
        Drawable drawable = getRightDrawables(2);
        //如果右边没有图片，不再处理
        if (drawable == null)
            return false;
        //如果不是按下事件，不再处理
        if (event.getAction() != MotionEvent.ACTION_UP)
            return false;
        if (event.getX() > idEditPassword.getWidth()
                - idEditPassword.getPaddingRight()
                - drawable.getIntrinsicWidth()) {
            inPassword();
        }
        return false;
    }

    /**
     * 密码显示隐藏
     */
    protected void inPassword() {
        if (idEditPassword.isSelected()) {
            idEditPassword.setSelected(false);
            setRightImage(R.drawable.login_ic_visibility_off);
            idEditPassword.setInputType(InputType.TYPE_CLASS_TEXT
                    | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        } else {
            idEditPassword.setSelected(true);
            setRightImage(R.drawable.login_ic_visibility_on);
            idEditPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        }
        idEditPassword.setSelection(idEditPassword.getText().length());
    }

    @Override
    protected void onGrantedSuccess() {
        loginSign.setOnClickListener(view -> {
            if (isGranted()) {
                setInstallPermission();
                return;
            }
            if (mLoginListener != null) {
                String account = getEditText(R.id.login_edit_account)
                        .getText()
                        .toString()
                        .trim();
                String password = getEditText(R.id.login_edit_password)
                        .getText()
                        .toString()
                        .trim();

                if (isAccount(account) && isPassword(password)) {
                    mLoginListener.onSignIn(account, password);
                }
            }
        });

    }

    /**
     * 右边按钮图片
     *
     * @param image：
     */
    private void setRightImage(int image) {
        try {
            setRightImage(ResourceUtils.getDrawable(image));
        } catch (Exception e) {
            LatteLogger.e(e.getMessage());
        }
    }

    /**
     * 右边按钮图片
     *
     * @param image：
     */
    private void setRightImage(Drawable image) {
        if (idEditPassword != null) {
            try {
                idEditPassword.setCompoundDrawablesWithIntrinsicBounds(getRightDrawables(0), getRightDrawables(1),
                        image, getRightDrawables(3));
            } catch (Exception e) {
                LatteLogger.e(e.getMessage());
            }
        }
    }

    public Drawable getRightDrawables(int i) {
        if (idEditPassword != null) {
            return idEditPassword.getCompoundDrawables()[i];
        }
        return null;
    }


    @Override
    public void afterTextChanged(Editable editable) {
        if (idEditPassword != null && loginSign != null) {
            loginSign.setEnabled(idEditPassword.getText().toString().trim().length() > 1);
        }
    }

}